package indi.lddsdu;

import indi.lddsdu.util.IndexUtil;
import indi.lddsdu.util.SearchUtil;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.IntField;
import org.apache.lucene.document.NumericDocValuesField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.search.*;
import org.junit.Test;

import java.io.IOException;

/**
 * Created by jack on 18/6/9.
 */
public class IntFieldTest {
    private static final String INDEX_PATH = "/Users/jack/Desktop/inputFieldPath";
    /**
     * 测试保存IntField
     */
    @Test
    public void testIndexFieldStored(){
        Document document = new Document();
        document.add(new IntField("intvalue", 30, Field.Store.YES));
        document.add(new NumericDocValuesField("intvalue", 30));
        Document document1 = new Document();
        document1.add(new IntField("intvalue", 40, Field.Store.YES));
        document1.add(new NumericDocValuesField("intvalue", 40));
        IndexWriter writer = null;

        try{
            writer = IndexUtil.getIndexWriter(INDEX_PATH, false);
            writer.addDocument(document);
            writer.addDocument(document1);

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (writer != null) {
                try {
                    writer.commit();
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    /**
     * 测试intField排序
     */
    @Test
    public void testIntFieldSort(){
        try{
            IndexSearcher searcher = SearchUtil.getIndexSearcher(INDEX_PATH);
            //构建排序字段
            SortField[] sortFields = new SortField[1];
            sortFields[0] = new SortField("intvalue", SortField.Type.INT, true);
            Sort sort = new Sort(sortFields);
            //查询所有结果
            Query query = new MatchAllDocsQuery();
            TopFieldDocs docs = searcher.search(query, 2, sort);
            ScoreDoc[] scores = docs.scoreDocs;
            //遍历结果
            for (ScoreDoc scoreDoc : scores){
                System.out.println(searcher.doc(scoreDoc.doc));
            }
        } catch (IOException e) {
            e.printStackTrace();

        }
    }
}
